package cn.historia.infrastructure.adapter.repository;


import cn.historia.domain.task.model.entity.TaskEntity;
import cn.historia.domain.task.repository.ITaskRepository;
import cn.historia.infrastructure.event.EventPublisher;
import cn.historia.infrastructure.persistent.dao.ITaskDao;
import cn.historia.infrastructure.persistent.po.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @package: cn.historia.infrastructure.adapter.repository
 * @className: TaskRepository
 * @author: 云溪
 * @description: 任务服务仓储实现
 * @date: 2025/9/30 16:01
 * @version: 1.0
 */
@Slf4j
@Repository
public class TaskRepository implements ITaskRepository {

    @Resource
    private ITaskDao taskDao;

    @Resource
    private EventPublisher eventPublisher;

    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        List<Task> tasks = taskDao.queryNoSendMessageTaskList();
        List<TaskEntity> taskEntities = new ArrayList<>(tasks.size());
        for (Task task : tasks) {
            taskEntities.add(
                    TaskEntity.builder()
                            .userId(task.getUserId())
                            .topic(task.getTopic())
                            .messageId(task.getMessageId())
                            .message(task.getMessage())
                            .build()
            );
        }

        return taskEntities;
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        Task taskReq = new Task();
        taskReq.setUserId(userId);
        taskReq.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(taskReq);
    }

    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        Task taskReq = new Task();
        taskReq.setUserId(userId);
        taskReq.setMessageId(messageId);
        taskDao.updateTaskSendMessageFail(taskReq);
    }
}
